import pygame
from plane_sprites import *

class PlaneGame(object):
    """飞机大战"""

    #游戏初始化
    def __init__(self):
        #print("游戏初始化")
        self.screen=screen
        pygame.display.set_caption("飞机大战")
        self.cur_enemy=None
        self.is_over=False
        self.is_pause=False
        self.score=0
        self.__create_sprites()
        self.clock=pygame.time.Clock()
        self.start_game()
        pass

    #游戏主逻辑
    def start_game(self):
        #print("游戏开始")
        pygame.time.set_timer(20,1000)
        while True:
            self.clock.tick(FRAME_PER_SEC)
            self.__event_handler()
            if self.is_over:
                self.game_over()
            elif self.is_pause:
                self.bg_group.update()
                self.bg_group.draw(self.screen)
                self.show_pause(0)
                pygame.display.update()
            else:
                self.__check_collide()
                self.__update_sprites()
                pygame.display.update()


    #创建精灵
    def __create_sprites(self):
        bg1=BackGround("./images/background.png")
        bg2=BackGround("./images/background.png")
        bg2.rect.y=-SCREEN_RECT.height

        self.hero=Hero()
        self.bg_group=pygame.sprite.Group(bg1,bg2)
        self.hero_group=pygame.sprite.Group(self.hero)
        self.enemy_group=pygame.sprite.Group()


    #事件监听
    def __event_handler(self):
        for e in pygame.event.get():
            if e.type==pygame.QUIT:#退出事件
                pygame.quit()
                exit(0)
            elif e.type==20:#创建敌军
                enemy=Enemy()
                enemy.fire()
                self.enemy_group.add(enemy)
            elif e.type==21:#创建子弹
                for enemy in self.enemy_group.sprites():
                    enemy.fire()
                self.hero.fire()
            elif e.type==22:#敌军销毁
                for i in (1, 2, 3, 4):
                    e.enemy.image = pygame.image.load("./images/enemy1_down%d.png" % i)
                    if screen:
                        screen.blit(e.enemy.image, e.enemy.rect)

            elif e.type==23:#英雄销毁
                for i in (1, 2, 3, 4):
                    e.hero.image = pygame.image.load("./images/me_destroy_%d.png" % i)
                    if screen:
                        screen.blit(e.hero.image, e.hero.rect)
                    pygame.display.update()
                    pygame.time.delay(100)
            elif e.type==pygame.MOUSEBUTTONDOWN:
                if self.is_over:
                    x=e.pos[0]
                    y=e.pos[1]
                    again_rect=self.again_rect
                    over_rect=self.over_rect
                    if again_rect.left<x<again_rect.right and again_rect.top<y<again_rect.bottom:#重新开始
                        #print("重新开始")
                        self.__init__()
                    elif over_rect.left<x<over_rect.right and over_rect.top<y<over_rect.bottom:#结束游戏
                        #print("结束游戏")
                        pygame.quit()
                        exit(0)
            elif e.type==pygame.KEYDOWN:
                if e.key==32:
                    self.is_pause=not self.is_pause
            else:
                pass


        keys=pygame.key.get_pressed()
        if keys[pygame.K_RIGHT] or keys[pygame.K_d]:#右键按下
            self.hero.speed=2
        elif keys[pygame.K_LEFT] or keys[pygame.K_a]:#左键按下
            self.hero.speed=-2
        elif keys[pygame.K_UP] or keys[pygame.K_w]:
            self.hero.rect.y+=-2
        elif keys[pygame.K_DOWN]  or keys[pygame.K_s]:
            self.hero.rect.y+=2
        else:
            self.hero.speed=0

    #碰撞检测
    def __check_collide(self):
        dict=pygame.sprite.groupcollide(self.hero.bullets,self.enemy_group,True,False)
        for enemy in dict.values():
            enemy[0].cur_HP-=20
            self.cur_enemy=enemy[0]
            if enemy[0].cur_HP<=0:
                enemy[0].kill()
                self.score+=100
        enemy_list=pygame.sprite.spritecollide(self.hero,self.enemy_group,True)
        if len(enemy_list):
            self.hero.cur_HP -= 50
            if self.hero.cur_HP <= 0:
                self.is_over=True
                e = pygame.event.Event(23, {"hero": self.hero})
                pygame.event.post(e)
        #英雄子弹与敌军子弹检测
        for enemy in self.enemy_group.sprites():
            pygame.sprite.groupcollide(self.hero.bullets,enemy.bullets,True,True)
            buttle_list = pygame.sprite.spritecollide(self.hero, enemy.bullets, True)
            if len(buttle_list):
                self.hero.cur_HP-=20
                if self.hero.cur_HP<=0:
                    self.is_over = True
                    e = pygame.event.Event(23, {"hero": self.hero})
                    pygame.event.post(e)
                pass

    #更新精灵
    def __update_sprites(self):
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        self.hero_group.update()
        self.hero_group.draw(self.screen)
        self.hero.bullets.update()
        self.hero.bullets.draw(self.screen)
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        for enemy in self.enemy_group.sprites():
            enemy.bullets.update()
            enemy.bullets.draw(self.screen)
        self.hero.show_HP()
        if self.cur_enemy is not None:
            self.cur_enemy.show_HP()
        self.show_pause(not self.is_pause)
        self.show_score()

    def game_over(self):
        #print("游戏结束")
        again_x = (SCREEN_RECT.width - 300) / 2
        again_y=(SCREEN_RECT.height - 41) / 2
        over_x=(SCREEN_RECT.width - 300) / 2
        over_y=(SCREEN_RECT.height - 41) / 2 - 81
        self.bg_group.update()
        self.bg_group.draw(self.screen)
        self.again = pygame.image.load("./images/again.png")
        self.over=pygame.image.load("./images/gameover.png")

        self.again_rect=pygame.Rect(again_x,again_y,self.again.get_width(),self.again.get_height())
        self.over_rect=pygame.Rect(over_x,over_y,self.over.get_width(),self.over.get_height())
        self.screen.blit(self.over, (over_x,over_y ))
        self.screen.blit(self.again,(again_x , again_y))
        pygame.display.update()

    def show_pause(self,flag=1):
        pause_image=pygame.image.load("./images/pause_nor.png")
        resume_image=pygame.image.load("./images/resume_nor.png")
        pause_x=(SCREEN_RECT.width-pause_image.get_width())/2
        pause_y=SCREEN_RECT.height-pause_image.get_height()-20
        if flag:
            screen.blit(pause_image,(pause_x,pause_y))
        else:
            screen.blit(resume_image, (pause_x, pause_y))

    def show_score(self):
        pygame.font.init()
        font_list = pygame.font.get_fonts()
        # font_name = pygame.font.get_default_font()
        self.font = pygame.font.Font(pygame.font.match_font(font_list[0]), 22)
        image = self.font.render("SCORE :%d" % self.score, True, [255, 0, 0], [255, 255, 255])
        screen.blit(image, (SCREEN_RECT.width-150, 20))


if __name__ == '__main__':
    game=PlaneGame()
